package com.jeesite.modules.isys.common.aop.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jeesite.modules.isys.common.aop.check.CheckEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 小野喵
 * @version 1.0
 * @description: TODO
 * @date 2023/11/4 15:42
 */

@Component
public class SearchSupport {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private QueryUtils queryUtils;



    private  Map<Class, IService> serviceMap = new HashMap<>();

    private IService  getService(Object obj){

        if (serviceMap == null || serviceMap.isEmpty()) {
            Map<String, IService> beansOfType = applicationContext.getBeansOfType(IService.class);

            if (!beansOfType.isEmpty()) {
                for (IService service : beansOfType.values()) {
                    if (service != null) {
                        Class<?> aClass = GenericTypeResolver.resolveTypeArgument(service.getClass(), IService.class);

                        //添加扫描到的bean
                        serviceMap.put(aClass, service);
                    }

                }
            }
        }


        return serviceMap.get(obj.getClass());
    }

    public List<Object> search(Object obj,Integer pageNo,Integer pageSize) throws IllegalAccessException {
        IService service = getService(obj);
        if (service == null){
            return  new ArrayList<>();
        }

        QueryWrapper queryWrapper = queryUtils.getQueryWrapper(obj);
        queryWrapper.last("limit "+(pageNo-1)*pageSize+","+(pageNo*pageSize));
        List list = service.getBaseMapper().selectList(queryWrapper);
        return list;
    }
}
